package com.bwsoft.admin.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Service;

import com.bwsoft.admin.domain.Advertisement;
import com.bwsoft.admin.domain.valueObject.AdvertisementVO;
import com.bwsoft.admin.service.AdService;
import com.bwsoft.api.util.Constant;
import com.bwsoft.model.Message;
import com.bwsoft.service.DictionaryDataService;
import com.bwsoft.util.UploadFileUtil;

@Service(AdService.NAME)
public class AdServiceImpl extends BaseServiceImpl_ybd implements AdService {

	private static Logger LOG = Logger.getLogger(AdService.class.getClass());
	@Resource(name =  DictionaryDataService.NAME)
	DictionaryDataService dictionaryDataService;
	//s_adName,  s_place,  s_status,  s_remark
	@Override
	public List<Advertisement> findData(Integer page, Integer rows,
			String s_adName, String s_place, String s_status, String s_remark) {
		StringBuffer adHql = new StringBuffer();
		
		Map<String, String> placeMap=dictionaryDataService.getDicDataByName("web_advertisement");
		
		adHql.append("from Advertisement as ad where 1=1");
		if(s_adName != null && !"".equals(s_adName.trim())){
			adHql.append(" and ad.adName like '%"+s_adName.trim()+"%'");
		}
		if(s_place != null && !"".equals(s_place.trim())){
			adHql.append(" and ad.place like '%"+s_place.trim()+"%'");
		}
		if(s_status != null && !"".equals(s_status.trim())){
			adHql.append(" and ad.status = '"+s_status.trim()+"'");
		}
		if(s_remark != null && !"".equals(s_remark.trim())){
			adHql.append(" and ad.remark like '%"+s_remark.trim()+"%'");
		}
		adHql.append(" order by ad.addTime desc");
		List<Advertisement> adData = advertisementDao.findPage(adHql.toString(), rows, (page - 1) * rows);
		for (Advertisement ad : adData) {
			if(ad.getPlace() != null)
			ad.setPlaceName(placeMap.containsKey(ad.getPlace().toString())?placeMap.get(ad.getPlace().toString()):"" );
		}
		return adData;
	}

	@Override
	public Long getTotalCount(String s_adName, String s_place, String s_status, String s_remark) {
		StringBuffer adHql = new StringBuffer();
		adHql.append("select count(*) from Advertisement as ad where 1=1");
		if(s_adName != null && !"".equals(s_adName.trim())){
			adHql.append(" and ad.adName like '%"+s_adName.trim()+"%'");
		}
		if(s_place != null && !"".equals(s_place.trim())){
			adHql.append(" and ad.place like '%"+s_place.trim()+"%'");
		}
		if(s_status != null && !"".equals(s_status.trim())){
			adHql.append(" and ad.status = '"+s_status.trim()+"'");
		}
		if(s_remark != null && !"".equals(s_remark.trim())){
			adHql.append(" and ad.remark like '%"+s_remark.trim()+"%'");
		}
		Long count;
		count = (Long)advertisementDao.findByHql(adHql.toString()).get(0);
		return count;
	}

	@Override
	public Message saveOrUpdateAd(Advertisement ad,File annex,String annexName) {
		Message msg = new Message();
		com.bwsoft.admin.domain.File filePojo = new com.bwsoft.admin.domain.File();
		try {
			ad.setAddTime(new Date());
			if(ad.getAdid() != null && !"".equals(ad.getAdid())){
				Advertisement updataBefor = advertisementDao.findById(ad.getAdid());
				ad.setAddTime(updataBefor.getAddTime());
				ad.setFile(updataBefor.getFile());
				ad.setStatus(updataBefor.getStatus());
			}
			//---------附件上传（如果没上传则取原数据库内容保存）--------------
			if(annex != null && !"".equals(annex)){
				Calendar now = Calendar.getInstance();
				String annexFilepath = ServletActionContext.getServletContext().getRealPath(Constant.PATH_IMG_AD+"/"+now.get(Calendar.YEAR)+(now.get(Calendar.MONTH) + 1));
				String annexFileName=null ;
				annexFileName=UUID.randomUUID().toString()+annexName.substring(annexName.lastIndexOf('.'), annexName.length());
				UploadFileUtil.uploadOneFile(annexFileName, annex, annexFilepath);
				filePojo.setPath(Constant.PATH_IMG_AD+"/"+now.get(Calendar.YEAR)+(now.get(Calendar.MONTH) + 1)+"/"+annexFileName);
				filePojo.setName(annexName);
				filePojo.setSize(String.valueOf(annex.length()));
				filePojo.setAddTime(new Date());
				ad.setFile(filePojo);
				ad.setStatus(false);
			}
			advertisementDao.saveOrUpdate(ad);
			msg.setMsgFlag(true);
			msg.setMsgStr("保存成功！");
		} catch (Exception e) {
			msg.setMsgFlag(false);
			msg.setMsgStr("保存失败：" + e.toString());
			LOG.info(e);
		}
		return msg;
	}

	@Override
	public Advertisement adModifyInfo(Integer id) {
		Advertisement advertisement=null;
		try{
			advertisement = advertisementDao.findById(id);
			advertisement.setPlaceName(dictionaryDataService.getDicValueDataByNameValue("web_advertisement", advertisement.getPlace()));
		}catch (Exception e) {
			e.printStackTrace();
		}
		return advertisement;
	}

	@Override
	public Message remove(String ids) {
		Message msg = new Message();
		try {
			StringBuffer adHql = new StringBuffer();
			adHql.append("delete from Advertisement ad where ad.adid in ("+ids+")"); 
			advertisementDao.executeByHql(adHql.toString());
			msg.setMsgFlag(true);
			msg.setMsgStr("保存成功！");
		} catch (Exception e) {
			msg.setMsgFlag(false);
			msg.setMsgStr("保存失败：" + e.toString());
			LOG.info(e);
		}
		return msg;
	}

	@Override
	public Message show(String ids) {
		Message msg = new Message();
		try {
//			StringBuffer adHql = new StringBuffer();
//			adHql.append("update Advertisement ad set ad.status=1 where ad.adid in ("+ids+")"); 
//			advertisementDao.executeByHql(bannerHql.toString());
			
			List<Advertisement> adData = advertisementDao.findByHql("select ad0 from Advertisement as ad0,Advertisement as ad1 where ad0.status = 1 and ad0.place = ad1.place and ad1.adid = "+ids);
			
			if(adData.size()>0){
//				advertisementDao.executeByHql("update Advertisement ad set ad.status=0 where ad.adid in ("+ids+")");
				msg.setMsgFlag(false);
				msg.setMsgStr("该位置已有显示的广告！名称为："+adData.get(0).getAdName());
				return msg;
			}
			advertisementDao.executeByHql("update Advertisement ad set ad.status=1 where ad.adid = "+ids);
			msg.setMsgFlag(true);
			msg.setMsgStr("保存成功！");
		} catch (Exception e) {
			msg.setMsgFlag(false);
			msg.setMsgStr("保存失败：" + e.toString());
			e.printStackTrace();
			LOG.info(e);
		}
		return msg;
	}

	@Override
	public Message hide(String ids) {
		Message msg = new Message();
		try {
			StringBuffer adHql = new StringBuffer();
			adHql.append("update Advertisement ad set ad.status=0 where ad.adid in ("+ids+")"); 
			advertisementDao.executeByHql(adHql.toString());
			msg.setMsgFlag(true);
			msg.setMsgStr("保存成功！");
		} catch (Exception e) {
			msg.setMsgFlag(false);
			msg.setMsgStr("保存失败：" + e.toString());
			LOG.info(e);
		}
		return msg;
	}

	@Override
	public Advertisement getAdByPos(Integer pos) {
		Advertisement advertisement = null;
		try{
			List<Advertisement> adData = advertisementDao.findByHql("from Advertisement ad where ad.status = 1 and ad.place = ?", pos);
			if (adData.size() > 0) {
				advertisement = adData.get(0);
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		return advertisement;
	}

	@Override
	public List<AdvertisementVO> getAdVo(List<Advertisement> ads) {
		List<AdvertisementVO> adVoList = new ArrayList<AdvertisementVO>();
		AdvertisementVO adVo = new AdvertisementVO();
		for (Advertisement ad : ads) {
			adVo = new AdvertisementVO();
			adVo.setAddTime(ad.getAddTime());
			adVo.setAdid(ad.getAdid());
			adVo.setAdName(ad.getAdName());
			adVo.setAdUrl(ad.getAdUrl());
			adVo.setPlaceName(ad.getPlaceName());
			adVo.setRemark(ad.getRemark());
			adVo.setStatus(ad.getStatus());
			adVo.setPlace(ad.getPlace());
			
			if(ad.getFile() != null && !"".equals(ad.getFile())){
				adVo.setFileId(ad.getFile().getId().toString());
				adVo.setFileName(ad.getFile().getName());
				adVo.setFilePath(ad.getFile().getPath());
				adVo.setFileSize(ad.getFile().getSize());
			}
			adVoList.add(adVo);
		}
		return adVoList;
	}
}
